package com.flyxiaozhu.erp.admin.controllers;

import com.flyxiaozhu.erp.core.entities.ExpressCompany;
import com.flyxiaozhu.erp.core.libs.ErrorCode;
import com.flyxiaozhu.erp.core.libs.JSONResult;
import com.flyxiaozhu.erp.core.libs.SearchSpecification;
import com.flyxiaozhu.erp.core.repositories.ExpressCompanyRepository;
import com.flyxiaozhu.erp.core.utils.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author flyxiaozhu
 * @date 2019-04-27 0:10
 */
@RestController
public class ExpressController {
    @Autowired
    ExpressCompanyRepository expressCompanyRepository;

    @RequestMapping(value = "/express/select")
    @Secured("ROLE_EXPRESS_SELECT")
    public JSONResult select(HttpServletRequest request, @PageableDefault(sort = {"sort"}, direction = Sort.Direction.ASC) Pageable pageable) {
        Page<ExpressCompany> page = expressCompanyRepository.findAll(new SearchSpecification<>(request), pageable);
        return new JSONResult(page, pageable.getPageNumber());
    }

    @RequestMapping(value = "/express/insert")
    @Secured("ROLE_EXPRESS_INSERT")
    public JSONResult insert(ExpressCompany company) {
        expressCompanyRepository.save(company);
        return new JSONResult().put("model", company).put("count", 1);
    }

    @RequestMapping(value = "/express/update")
    @Secured("ROLE_EXPRESS_UPDATE")
    public JSONResult update(ExpressCompany company) {
        expressCompanyRepository.save(company);
        return new JSONResult().put("model", company).put("count", 1);
    }

    @RequestMapping(value = "/express/delete")
    @Secured("ROLE_EXPRESS_DELETE")
    public JSONResult delete(@RequestParam String keys) {
        List<Long> ids = CollectionUtils.map(keys.split(","), o -> Long.parseLong(o));
        List<ExpressCompany> expressCompanies = expressCompanyRepository.findByIdIn(ids);
        if (expressCompanies.size() != ids.size()) {
            return new JSONResult(ErrorCode.NO_DATA, "标签id错误");
        }

        expressCompanyRepository.deleteAll(expressCompanies);
        return new JSONResult().put("count", expressCompanies.size()).put("model", expressCompanies);
    }
}
